package com.caiyi.financial.nirvana.sms.aspect;


import com.alibaba.fastjson.JSONObject;
import com.caiyi.financial.nirvana.sms.entity.SmsAdmin;
import com.caiyi.financial.nirvana.sms.entity.SmsLog;
import com.caiyi.financial.nirvana.sms.mapper.SmsLogMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

@Aspect
@Component
public class LoginOperateLogAspect {

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private SmsLogMapper logMapper;

    @Pointcut(value = "execution(* com.caiyi.financial.nirvana.sms.controller.AdminController.login(..))")
    public void pointCutMethod() {
    }

    @AfterReturning(pointcut = "pointCutMethod()", returning = "result")
    public void doAfterReturning(JoinPoint joinPoint, Object result) {
        try {
            SmsLog log = new SmsLog();
            Subject subject = SecurityUtils.getSubject();
            SmsAdmin admin = (SmsAdmin) subject.getPrincipal();
            if (admin != null) {
                log.setAccount(admin.getAccount());
                log.setIp(request.getRemoteAddr());
                String methodName = joinPoint.getSignature().getName();
                log.setMethod(methodName);
                log.setType(4);
                //获取请求参数
                StringBuilder parameter = new StringBuilder();
                Enumeration<String> paramNames = request.getParameterNames();
                while (paramNames.hasMoreElements()) {
                    String paramName = paramNames.nextElement();
                    String paramValue = request.getParameter(paramName);
                    if (parameter.length() == 0) {
                        parameter.append(paramName + "=" + paramValue);
                    } else {
                        parameter.append("&" + paramName + "=" + paramValue);
                    }
                }
                log.setParameter(parameter.toString());
                log.setResponse(JSONObject.toJSONString(result));
                logMapper.insertSelective(log);
            }
        } catch (Exception e) {
            logger.error("login log operate...", e);
        }
    }
}
